<template>
  <div class="timer-container">
    <h1 class="timer-title">计时器</h1>
    <p class="timer-desc">监控事物的持续时间，基本上是一种具有简单计时功能的计时器。</p>

    <div class="timer-display">{{ formatTime(hours) }}:{{ formatTime(minutes) }}:{{ formatTime(seconds) }}.{{ formatMilliseconds(milliseconds) }}</div>

    <div class="timer-controls">
      <button class="timer-btn" :class="{ start: !isRunning, stop: isRunning }" @click="toggleTimer">
        {{ isRunning ? '停止' : '开始' }}
      </button>
      <button class="timer-btn reset" @click="resetTimer">重置</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from 'vue'

// 计时器状态
const isRunning = ref(false)
const hours = ref(0)
const minutes = ref(0)
const seconds = ref(0)
const milliseconds = ref(0)
let intervalId = null

// 格式化时间，保证两位数显示
const formatTime = (value) => {
  return value.toString().padStart(2, '0')
}

// 格式化毫秒，保证三位数显示
const formatMilliseconds = (value) => {
  return value.toString().padStart(3, '0')
}

// 更新计时器
const updateTimer = () => {
  milliseconds.value += 10
  if (milliseconds.value >= 1000) {
    milliseconds.value = 0
    seconds.value++
    if (seconds.value >= 60) {
      seconds.value = 0
      minutes.value++
      if (minutes.value >= 60) {
        minutes.value = 0
        hours.value++
      }
    }
  }
}

// 开始/停止计时器
const toggleTimer = () => {
  if (isRunning.value) {
    clearInterval(intervalId)
  } else {
    intervalId = setInterval(updateTimer, 10)
  }
  isRunning.value = !isRunning.value
}

// 重置计时器
const resetTimer = () => {
  clearInterval(intervalId)
  isRunning.value = false
  hours.value = 0
  minutes.value = 0
  seconds.value = 0
  milliseconds.value = 0
}

// 组件卸载时清除定时器
onUnmounted(() => {
  clearInterval(intervalId)
})
</script>

<style scoped>
.timer-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  text-align: center;
}

.timer-title {
  font-size: 24px;
  margin-bottom: 10px;
  color: #333;
}

.timer-desc {
  color: #666;
  margin-bottom: 30px;
}

.timer-display {
  font-size: 48px;
  font-family: monospace;
  background-color: #1e1e1e;
  color: #fff;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 30px;
  text-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
}

.timer-controls {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.timer-btn {
  padding: 10px 20px;
  font-size: 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.start {
  background-color: #28a745;
  color: white;
}

.stop {
  background-color: #dc3545;
  color: white;
}

.reset {
  background-color: #6c757d;
  color: white;
}

.timer-btn:hover {
  opacity: 0.9;
  transform: scale(1.05);
}
</style>
